/**
 * 分段函数规则化：将分段参数转成分段函数的格式
 * @param {String} valField 数据的属性字段，该字段的值应为number
 * @param {Array} stepArray 分段参数, 由多个分段值和颜色值组成；要求必须是升序
 * @example: [{ step: 20, color: '#A6E181' }, { step: 50, color: '#E8E225' }, { step: 100, color: '#DE683C' }]
 * @param {color} lesser_color 设置小于最小值时的颜色
 * @returns {lisp} step
 * @example:[ 'step', [ 'get', 'total' ], '#FFFFFF', 20, '#A6E181', 50, '#E8E225', 100, '#DE683C']
 */
export function format_step(valField, stepArray, lesser_color = '#FFFFFF') {
  const lisp = ['step',
    ['get', valField],
    lesser_color
  ]
  stepArray.forEach(step => {
    lisp.push(step.step, step.color)
  })
  return lisp
}

/**
 * 分段函数规则化：将分段函数转成分段参数的格式
 * @param {lisp} step_lisp
 * @example:[ 'step', [ 'get', 'total' ], '#FFFFFF', 20, '#A6E181', 50, '#E8E225', 100, '#DE683C']
 * @returns {object}
 * @example { lesser_color: '#FFFFFF', list: [ { setp: 0, color: '#51bbd6' }, { setp: 10, color: '#51bbd6' }, { setp: 50, color: '#51bbd6' } ]}
 */
export function unformat_step(step_lisp) {
  const lesser_color = step_lisp[2]

  const list = []
  for (let i = 3; i < step_lisp.length; i++) {
    const step = {
      setp: step_lisp[i],
      color: step_lisp[i + 1]
    }
    list.push(step)
    ++i
  }

  return {
    lesser_color,
    list
  }
}

/**
 * 线性插值函数规则化：将线性插值参数转成线性插值函数的格式
 * @param {String} valField 数据的属性字段，该字段的值应为number
 * @param {Array} stepArray 线性插值参数, 由多个线性插值值和颜色值组成；要求必须是升序
 * @example: [{ step: 20, val: '#A6E181' }, { step: 50, val: '#E8E225' }, { step: 100, val: '#DE683C' }]
 * @example: [{ step: 5, val: 10 }, { step: 10, val: 12 }, { step: 20, val: 16 }]
 * @returns {lisp} step
 * @example:[ 'interpolate', [ 'linear' ], [ 'get', 'total' ], 20, '#A6E181', 50, '#E8E225', 100, '#DE683C' ]
 * @example: [ 'interpolate', [ 'linear' ], [ 'zoom' ], 5, 10, 10, 12, 20, 16 ]
 */
export function format_interpolate_linear(valField, stepArray) {
  let filed
  if (valField === 'zoom') {
    filed = ['zoom']
  } else {
    filed = ['get', valField]
  }

  const lisp = [
    'interpolate',
    ['linear'], filed
  ]
  stepArray.forEach(step => {
    lisp.push(step.step, step.val)
  })
  return lisp
}
/**
 * 线性插值函数规则化：将线性插值函数转成线性插值参数的格式
 * @param {lisp} step_lisp
 * @example:[ 'interpolate', [ 'linear' ], [ 'get', 'total' ], 20, '#A6E181', 50, '#E8E225', 100, '#DE683C' ]
 * @example: [ 'interpolate', [ 'linear' ], [ 'zoom' ], 5, 10, 10, 12, 20, 16 ]
 * @returns {object}
 * @example { filed: 'zoom', list: [ { setp: 5, val: 10 }, { setp: 10, val: 12 }, { setp: 20, val: 16 } ]}
 */
export function unformat_interpolate_linear(step_lisp) {
  const filed_exp = step_lisp[2]
  const filed = filed_exp[filed_exp.length - 1]

  const list = []
  for (let i = 3; i < step_lisp.length; i++) {
    const step = {
      setp: step_lisp[i],
      val: step_lisp[i + 1]
    }
    list.push(step)
    ++i
  }

  return {
    filed,
    list
  }
}

